﻿Imports OMANE.Common.UI
Imports OMANE.Common
Imports System.ComponentModel
Imports PTIC_Util
Imports System.Windows.Input
Imports OMANE.Modules.TauxGarantis.moteurTauxGaranti1
Imports System.Windows.Forms
Imports PTIC_Util.GestionCalculs
Imports PTIC_GestionBDD
Imports System.Windows.Controls
Imports System.Xml.Serialization
Imports System.Windows
Imports Microsoft.Practices.Prism.Commands


Namespace ViewModels
    Public Class ViewModelScenarioCentral
        Inherits ViewModelCommand
        Implements IViewModelTabSection

        Private _Model As IModelTauxGarantis
        Public Sub New(ByVal Model As IModelTauxGarantis, ByVal DisplayName As String, ByVal Command As ICommand)
            MyBase.DisplayName = DisplayName
            _Model = Model
            Title = "SCENARIO CENTRAL"
        End Sub
        Sub New()
        End Sub

        Public Property Icone As String Implements Common.UI.IViewModelTabSection.Icone
        Public Property Title As String Implements Common.UI.IViewModelTabSection.Title
        Public Property IsClosable As Boolean Implements IViewModelTabSection.IsClosable

        Public Property TypeCode As TypeCode
            Get
                Return Locator.ModelStatic.ListeTraitements.TypeCode
            End Get
            Set(value As TypeCode)
                If value <> Locator.ModelStatic.ListeTraitements.TypeCode Then
                    OnPropertyChanging("TypeCode")
                    'Dans la liste des traitement, procéder au changement
                    Locator.ModelStatic.ListeTraitements.TypeCode = value
                    'Invalider le moteur de calcul du scénario central
                    'Générer un évènement pour indiquer le changement de la propriété au ViewModel
                    OnPropertyChanged("ResultatsScenarioCentral")
                    OnPropertyChanged("TypeCode")
                End If
            End Set
        End Property

        Private HandlerActif As Boolean = False
        Public ReadOnly Property ActiverCodeVBNET As Boolean
            Get
                'Permet de contourner l'impossibilité d'inclure dans le constructeur l'interception de l'évènement
                If Not HandlerActif Then
                    AddHandler Locator.ModelStatic.ListeTraitements.TablesBCACChanged, AddressOf OnTablesBCACChanged
                    HandlerActif = True
                End If
                Return Locator.ModelStatic.ListeTraitements.TablesBCAC = False
            End Get
        End Property

        'Intercepter l'évènement indiquant un changement de TableBCAC pour mettre à jour la propriété ActiverCodeVBNET
        Private Sub OnTablesBCACChanged(sender As Object, e As PTIC_Util.PropertyChangeEventArgs(Of Boolean))
            'MsgBox("La propriété TableBCAC de la liste des traitements a été modifiée")
            OnPropertyChanged("TypeCode")
            OnPropertyChanged("ActiverCodeVBNET")
        End Sub

        Public Sub refresh()
            OnPropertyChanged("ResultatsScenarioCentral")
        End Sub

        Public ReadOnly Property SegmentsRetenus() As ObservableDictionary(Of String, Correspondance)
            Get
                Return Locator.ModelStatic.Segmentation.Retenue
            End Get
        End Property
        Public ReadOnly Property ResultatsScenarioCentral As resultatsMoteur1
            Get
                Return Locator.ModelStatic.ListeTraitements.TraitMoteurMethode1.ScenarioCentral.resultats
            End Get
        End Property
        Public ReadOnly Property NiveauMutualisation As IEnumerable
            Get
                Return Locator.ModelStatic.Segmentation.Retenue
            End Get
        End Property
        Private _test As Double = 0.12
        Public Property CommissionContractante As Double
            Get
                Return If(Locator.ModelStatic Is Nothing, Math.Min(0.999, Math.Max(0.001, _test)), Locator.ModelStatic.ListeParametres.Tx_CommiContA.ValeurUnique)
            End Get
            Set(ByVal value As Double)
                OnPropertyChanging("CommissionContractante")
                If (Locator.ModelStatic Is Nothing) Then
                    _test = Math.Min(0.999, Math.Max(0.001, value))
                Else
                    Locator.ModelStatic.ListeParametres.Tx_CommiContA.ValeurUnique = (value)
                End If

                OnPropertyChanged("CommissionContractante")
            End Set
        End Property
        Public ReadOnly Property CommissionContractanteSegmente As DataTable
            Get
                Return Locator.ModelStatic.ListeParametres.Tx_CommiContA.Valeurs
            End Get
        End Property

#Region "Les commandes"
        Private _CalculerScenarioCentralCommand As New DelegateCommand(Of Object)(AddressOf CalculerScenarioCentralExecute, AddressOf CalculerScenarioCentralCanExecute)
        Public ReadOnly Property CalculerScenarioCentralCommand As DelegateCommand(Of Object)
            Get
                Return _CalculerScenarioCentralCommand
            End Get
        End Property
        Private Sub CalculerScenarioCentralExecute(ByVal parameter As Object)
            Dim old = System.Windows.Input.Mouse.OverrideCursor
            System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting
            Dim moteurCalcul As IIntegMoteur_MethodeEqTarif
            moteurCalcul = Locator.ModelStatic.ListeTraitements.TraitMoteurMethode1
            moteurCalcul.listeParametres = Locator.ModelStatic.ListeParametres
            'moteurCalcul.init_tbles_travail()
            moteurCalcul.calculerScenarioCentral()
            System.Windows.Input.Mouse.OverrideCursor = old
            OnPropertyChanged("ResultatsScenarioCentral")
            'Afficher les onglets de simulation

        End Sub
        Private Function CalculerScenarioCentralCanExecute(ByVal parameter As Object) As Boolean
            'Dim result As ResultatValidationContraintes
            'Valider la liste de paramètres
            'result = controleListeParametres.isListeParametresValide()
            'If Not result.IsValide Then
            '    MsgBox("Le scénario central de la méthode 1 ne peut pas être exécuté car : " & vbCrLf & vbCrLf & result.Msg)
            '    Return False
            'Else
            '    Return True
            'End If
            Return True
        End Function

        Private _EffectuerSimulationsCommand As New DelegateCommand(Of Object)(AddressOf EffectuerSimulationsExecute, AddressOf EffectuerSimulationsCanExecute)
        Public ReadOnly Property EffectuerSimulationsCommand As DelegateCommand(Of Object)
            Get
                Return _EffectuerSimulationsCommand
            End Get
        End Property
        Private Sub EffectuerSimulationsExecute(ByVal parameter As Object)
            'MsgBox("Demande de calcul des simuations")
            'Dim moteurCalcul As Moteur_Methode1 = _Model.Univers.listeTraitements.TraitMoteurMethode1
            'moteurCalcul.calculerSimulations()
            Dim old = System.Windows.Input.Mouse.OverrideCursor
            System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting

            If info IsNot Nothing Then
                info.Dispose()
                info = Nothing
            End If
            info = New Common.AsynchronousOperationInfo()
            With info
                .CanReportProgres = True
                .ShowUI = True
            End With
            ModuleTauxGaranti._app.StartAsyncOperation(New Common.AsynchronousOperationHandler(AddressOf DoWork), _
                   info)

            System.Windows.Input.Mouse.OverrideCursor = old
        End Sub
        Private Function EffectuerSimulationsCanExecute(ByVal parameter As Object) As Boolean
            Return True
        End Function

        Private _ExporterVersExcelCommand As New DelegateCommand(Of Object)(AddressOf ExporterVersExcelExecute, AddressOf ExporterVersExcelCanExecute)
        Public ReadOnly Property ExporterVersExcelCommand As DelegateCommand(Of Object)
            Get
                Return _ExporterVersExcelCommand
            End Get
        End Property
        Private Sub ExporterVersExcelExecute(ByVal parameter As Object)
            Dim SaveFileDialog1 As New SaveFileDialog
            SaveFileDialog1.InitialDirectory = csteEmplacementSorties
            SaveFileDialog1.Filter = "Fichiers Excel|*.xls;*.xlsx"

            If SaveFileDialog1.ShowDialog() = DialogResult.OK Then

                Dim old = System.Windows.Input.Mouse.OverrideCursor
                System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting

                Dim b As Boolean
                Dim xlEtude As New gestionExcelTxGar1OMANE(b, Locator.ModelStatic, Locator.ModelStatic.ListeParametres)
                xlEtude.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual
                xlEtude.CalculateBeforeSave = False

                If b Then

                    xlEtude.ExcelAffParamFichier()
                    xlEtude.ExcelAffParamTranches()
                    xlEtude.ExcelAffParamGeneraux()
                    xlEtude.ExcelAffSegmentation()
                    xlEtude.ExcelAffResDetaillesScenCentral()
                    xlEtude.DisplayAlert = False
                    xlEtude.EnregistrerSous(SaveFileDialog1.FileName)
                    xlEtude.DisplayAlert = True
                    xlEtude.ChangerDeFeuilleActive("Legende - mode d'emploi")
                    xlEtude.Visible = True

                End If

                System.Windows.Input.Mouse.OverrideCursor = old

            End If
        End Sub
        Private Function ExporterVersExcelCanExecute(ByVal parameter As Object) As Boolean
            Return True
        End Function
#End Region

#Region "Calcul asynchrone des resultats"
        Private info As Common.AsynchronousOperationInfo
        Private Sub DoWork(ByVal [Module] As Type, ByVal Data() As Object)
            FonctionCalculComposee.EnableParallelism = False
            ModuleTauxGaranti.currentasyncinfo = info
            Dim moteurCalcul As IIntegMoteur_MethodeEqTarif = Locator.ModelStatic.ListeTraitements.TraitMoteurMethode1
            moteurCalcul.calculerSimulations()
        End Sub
#End Region

    End Class

    Public Class ViewModelCalculDetailleOption
        Inherits ViewModelBase

        Dim grid As Windows.Controls.DataGrid

        Sub New(ByVal grid As System.Windows.Controls.DataGrid)
            Me.grid = grid
        End Sub

        Private _Columns As New ObjectModel.ObservableCollection(Of ViewModelCalculDetailleGridColumnOption)
        Public Property Columns As ObjectModel.ObservableCollection(Of ViewModelCalculDetailleGridColumnOption)
            Get
                Return _Columns
            End Get
            Set(ByVal value As ObjectModel.ObservableCollection(Of ViewModelCalculDetailleGridColumnOption))
                OnPropertyChanging("Columns")
                _Columns = value
                OnPropertyChanged("Columns")
            End Set
        End Property


        Private _SaveParametresCommand As New DelegateCommand(Of Object)(AddressOf SaveParametresExecute, AddressOf SaveParametresCanExecute)
        Public ReadOnly Property SaveParametresCommand As DelegateCommand(Of Object)
            Get
                Return _SaveParametresCommand
            End Get
        End Property
        Private Sub SaveParametresExecute(ByVal parameter As Object)
            Dim sdlg As New SaveFileDialog()
            If sdlg.ShowDialog() = DialogResult.OK Then
                Dim ser = New XmlSerializer(GetType(ViewModelCalculDetailleGridColumnOption()))
                Dim f = IO.File.Open(sdlg.FileName, IO.FileMode.OpenOrCreate)
                ser.Serialize(f, Columns.ToArray())
                f.Close()
                f.Dispose()
                f = Nothing
            End If
        End Sub
        Private Function SaveParametresCanExecute(ByVal parameter As Object) As Boolean
            Return True
        End Function

        Private _LoadParametresCommand As New DelegateCommand(Of Object)(AddressOf LoadParametresExecute, AddressOf LoadParametresCanExecute)
        Public ReadOnly Property LoadParametresCommand As DelegateCommand(Of Object)
            Get
                Return _LoadParametresCommand
            End Get
        End Property
        Friend Sub LoadParametresExecute(ByVal parameter As Object)
            Dim filename As String = Nothing
            Dim data As ViewModelCalculDetailleGridColumnOption()
            Dim f As IO.Stream
            If parameter IsNot Nothing Then


            Else
                Dim odlg As New OpenFileDialog()
                If odlg.ShowDialog() = DialogResult.OK Then
                    filename = odlg.FileName
                Else
                    Return
                End If
            End If

            Dim ser = New XmlSerializer(GetType(ViewModelCalculDetailleGridColumnOption()))
            '    f = If(filename Is Nothing, parameter, IO.File.Open(filename, IO.FileMode.OpenOrCreate))
            f = If(filename Is Nothing, parameter, IO.File.Open(filename, IO.FileMode.OpenOrCreate))
            data = CType(ser.Deserialize(f), ViewModelCalculDetailleGridColumnOption())

            f.Close()
            f.Dispose()
            f = Nothing




            Dim q = From e In grid.Columns
                    Join c In data On e.Header.ToString() Equals c.ColumnName
                    Select New ViewModelCalculDetailleGridColumnOption(e, c)

            Columns = New ObjectModel.ObservableCollection(Of ViewModelCalculDetailleGridColumnOption)(q.AsEnumerable())

        End Sub
        Private Function LoadParametresCanExecute(ByVal parameter As Object) As Boolean
            Return True
        End Function

    End Class

    <Serializable()> _
    Public Class ViewModelCalculDetailleGridColumnOption
        Inherits ViewModelBase

        Dim brother As DataGridBoundColumn


        Sub New()

        End Sub

        Sub New(ByVal gridcol As DataGridBoundColumn)
            Me.brother = gridcol
        End Sub

        Sub New(ByVal gridcol As DataGridBoundColumn, ByVal twin As ViewModelCalculDetailleGridColumnOption)
            Me.brother = gridcol
            Visible = twin.Visible
            Format = twin.Format
            FormatPredefini = twin.FormatPredefini
            ColumnName = twin.ColumnName
            Alignment = twin.Alignment
            Formula = twin.Formula
        End Sub

        Private _Visible As Boolean
        Public Property Visible As Boolean
            Get
                Return If(brother Is Nothing, _Visible, brother.Visibility = Windows.Visibility.Visible)
            End Get
            Set(ByVal value As Boolean)
                OnPropertyChanging("Visible")
                If brother Is Nothing Then
                    _Visible = value
                Else
                    brother.Visibility = If(value, Windows.Visibility.Visible, Windows.Visibility.Collapsed)
                End If
                OnPropertyChanged("Visible")
            End Set
        End Property

        Private _Format As String
        Public Property Format As String
            Get
                Return If(brother Is Nothing, _Format, brother.Binding.StringFormat)
            End Get
            Set(ByVal value As String)
                OnPropertyChanging("Format")
                If brother Is Nothing Then
                    _Format = value
                Else
                    'bindinge()
                    Dim b As System.Windows.Data.Binding = TryCast(brother.Binding, System.Windows.Data.Binding)
                    brother.Binding = New System.Windows.Data.Binding(b.Path.Path) With {.StringFormat = value}
                End If
                OnPropertyChanged("Format")
            End Set
        End Property


        Private _FormatPredefiniCollection As IEnumerable

        <XmlIgnore()> _
        Public ReadOnly Property FormatPredefiniCollection As IEnumerable
            Get
                If _FormatPredefiniCollection Is Nothing Then
                    Dim o1 = New With {.Name = "Pourcentage", .Value = "0.00%"}
                    Dim o2 = New With {.Name = "Grand Nombre", .Value = "N0"}
                    _FormatPredefiniCollection = {o1, o2}
                End If
                Return _FormatPredefiniCollection
            End Get
        End Property

        Private _FormatPredefini As Object
        Public Property FormatPredefini As Object
            Get
                Return _FormatPredefini
            End Get
            Set(ByVal value As Object)
                OnPropertyChanging("FormatPredefini")
                _FormatPredefini = value
                Format = If(value Is Nothing, Format, value.Value)
                OnPropertyChanged("FormatPredefini")
            End Set
        End Property

        Private _ColumnName As String
        Public Property ColumnName As String
            Get
                Return If(brother Is Nothing, _ColumnName, brother.Header.ToString())
            End Get
            Set(ByVal value As String)
                OnPropertyChanging("ColumnName")
                If brother Is Nothing Then
                    _ColumnName = value
                Else
                    brother.Header = value
                End If
                OnPropertyChanged("ColumnName")
            End Set
        End Property

        Private _Alignment As Object = System.Windows.HorizontalAlignment.Left
        Public Property Alignment As Object
            Get
                If brother Is Nothing Then
                    Return _Alignment
                Else
                    If brother.ElementStyle Is Nothing Then
                        Return _Alignment
                    Else
                        Dim q = From e As Setter In brother.ElementStyle.Setters
                                Where e.Property Is System.Windows.Controls.Control.HorizontalAlignmentProperty
                                Select e.Value

                        Return q.FirstOrDefault()
                    End If
                End If
            End Get
            Set(ByVal value As Object)
                OnPropertyChanging("Alignment")
                If brother Is Nothing Then
                    _Alignment = value
                Else
                    If brother.ElementStyle Is Nothing Then
                        Dim s = New Style()
                        's.Setters.Add(
                        '  New Setter(ContentControl.HorizontalContentAlignmentProperty, value))
                        s.Setters.Add(
                           New Setter(System.Windows.Controls.Control.HorizontalAlignmentProperty, [Enum].ToObject(GetType(System.Windows.HorizontalAlignment), CInt(value))))
                        brother.ElementStyle = s
                    Else
                        Dim s = New Style()
                        's.Setters.Add(
                        '  New Setter(ContentControl.HorizontalContentAlignmentProperty, value))
                        s.Setters.Add(
                         New Setter(System.Windows.Controls.Control.HorizontalAlignmentProperty, [Enum].ToObject(GetType(System.Windows.HorizontalAlignment), CInt(value))))

                        brother.ElementStyle = s
                    End If
                End If
                OnPropertyChanged("Alignment")
            End Set
        End Property

        Private _Formula As String
        Public Property Formula As String
            Get
                Return _Formula
            End Get
            Set(ByVal value As String)
                OnPropertyChanging("Formula")
                _Formula = value
                OnPropertyChanged("Formula")
            End Set
        End Property


        <XmlIgnore()> _
        Public ReadOnly Property SupportFormula As Boolean
            Get
                Return Not String.IsNullOrEmpty(_Formula)
            End Get
        End Property


    End Class
End Namespace